#pragma once

#include <iostream>
#include <memory>
#include <string>
#include <cstring>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Comm.hpp"
#include "nocopy.hpp"

const static int16_t defaultport = 8888;
const static int defaultlisten = 5;

class TcpServer : public nocopy
{
public:
    TcpServer(int16_t port = defaultport) : _port(port), _isrunning(false)
    {
    }
    void Init()
    {
        // 创建socket
        _listenfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listenfd < 0)
        {
            std::cout << "create socket fail:" << strerror(errno) << std::endl;
            exit(Socket_Err);
        }
        std::cout << "create socket sucess,listenfd:" << _listenfd << std::endl;

        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = INADDR_ANY;
        // 绑定bind
        if (bind(_listenfd, CONV(server), sizeof(server)) != 0)
        {
            std::cout << "create bind fail" << strerror(errno) << std::endl;
            exit(Bind_Err);
        }
        std::cout << "create bind sucess,listenfd:" << _listenfd << std::endl;

        // 将listenfd设置成监听状态
        if (listen(_listenfd, defaultlisten) != 0)
        {
            std::cout << "create listen fail" << strerror(errno) << std::endl;
            exit(Listen_Err);
        }
        std::cout << "create listen sucess,listenfd:" << _listenfd << std::endl;
    }

    void server(int sock)
    {
        while(true)
        {
            char buffer[1024];
            ssize_t n =read(sock,buffer,sizeof(buffer)-1);
            if(n>0)
            {
                buffer[n]=0;
                std::cout<<"client say#"<<buffer<<std::endl;
                std::string info="server echo#";
                info+=buffer;
                write(sock,info.c_str(),sizeof(info));
            }
            else if(n==0)
            {
                std::cout<<"client quit..."<<std::endl;
                break;
            }
            else{
                std::cout<<"read sockfd fail"<<std::endl;
                break;
            }
        }
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listenfd, CONV(peer), &len);
            if (sockfd < 0)
            {
                std::cout << "create accept fail: " << strerror(errno) << std::endl;
                continue;
                ;
            }
            std::cout << "create accept sucess,sockfd:" << sockfd << std::endl;

            server(sockfd);

            close(sockfd);
        }
    }
    ~TcpServer() 
    {
        close(_listenfd);
    }

private:
    int16_t _port;
    int _listenfd;
    bool _isrunning;
};